/*
 	Script: GearsORM.ResultIterator.js
 	        Contains the ResultIterator class.
 	
 	License:
 	        MIT-style license.
*/

/*
 Class: GearsORM.ResultIterator
 	a iterator on a Google Gears ResultSet
 	
 Parameters:
 	result - the ResultSet to iterate
 	modelClass - the model class used to map the results 
 */
GearsORM.ResultIterator = function(result,modelClass)
{
	this.result = result;
	this.modelClass = modelClass;
	this.first = true;
};

GearsORM.ResultIterator.prototype = 
{
	//TODO:add a function to retrive results as raw objects
	/*
	 Function: next
	  	return the next row in the ResultSet as a model instance,if it is the last row it will return false.
	 */
	next:function()
	{
		if(!this.first)
			this.result.next();
		else
			this.first = false;
			
		return this.result.isValidRow() ? new this.modelClass()._populateFromResult(this.result) : this.close();
	},
	/*
	 Function: each
	  	a function to iterate the ResultSet like ruby each.
	 
	 Parameters:
	 	fn - function to be called for each row in the ResultSet
	 	bind - this will be used as this for the function,optional
	 */
	each:function(fn,bind)
	{
		var current;
		while(current = this.next())fn.apply(bind || this,[current]);
	},
	/*
	 Function: close
	  	close the ResultSet,this will be done automaticlly if the ResultSet is iterated to the end.
	  	if you don`t finish iterate the ResultSet this need to be called manually.
	 */
	close:function()
	{
		this.result.close();
		return false;
	},
	/*
	 Function: getOne
	  	return the first row of the ResultSet,will return false if the ResultSet is empty.
	 */
	getOne:function()
	{
		var instance = this.next();
		this.close();
		return instance;
	},
	/*
	 Function: toArray
	  	return the ResultSet as Array of model instances
	 */
	toArray:function()
	{
		var arr = [];
		this.each(arr.push,arr);
		return arr;
	}
};